"""
登录
"""
import time
import json
import logging

from common.models import TbMiniappUser
from src.utils import wx, record, hxIm
from common.tool.userTool import checkPassword
from src.utils.makeJwt import jwt_encode

errlog = logging.getLogger("err")


class LoginDirector:
    def __init__(self):
        self.wx = wx.WeChatLogin()
        self.wxpayApi = wx.WxPayApi()
        self.ur = record.UserRecord()
        self.hxapi = hxIm.HxApi()

    def login(self, **kwargs):
        """
        登录
        """
        code = kwargs.get("code")
        login_code = kwargs.get("login_code")
        # 登录
        phone_result = self.wx.get_user_phone_number(code)
        errcode = phone_result.get("errcode")
        if errcode == 0:
            phone_info = phone_result.get("phone_info")
            phoneNumber = phone_info.get("phoneNumber")
            password = "wechat"
            userExit = self.ur.exits_record(username=phoneNumber)
            if userExit:
                # 登录
                user: TbMiniappUser = self.ur.get_record_condition(username=phoneNumber)
                if checkPassword(user, password):
                    payload = {
                        "username": phoneNumber,
                        "password": password,
                        "create_time": time.time(),
                    }
                    token = jwt_encode(payload)
                else:
                    raise ValueError("密码错误")
            else:
                # 注册
                user_Info = {
                    "username": phoneNumber,
                    "password": password,
                    "phone": phoneNumber,
                    "wallet_balance": 0,
                    "name": phoneNumber,
                    "score": 0,
                    "gender": 1,
                }
                user: TbMiniappUser = self.ur.create_record(**user_Info)
                # 注册环信
                self.register_hx(username=phoneNumber, password=password)
                # 生成token
                payload = {
                    "username": phoneNumber,
                    "password": password,
                    "create_time": time.time(),
                }
                token = jwt_encode(payload)
        else:
            raise ValueError(json.dumps(phone_result))
        # 保存open_id
        if user.mini_openid is None:
            open_id = self.wxpayApi.get_openid(code=login_code)
            user.mini_openid = open_id
            user.save()
        return token

    def register_hx(self, **kwargs):
        """
        注册环信
        """
        username = kwargs.get("username")
        password = kwargs.get("password")
        info = {
            "password": password,
            "username": username,
        }
        login_result = self.hxapi.register_user(**info)
        print(login_result)
